package com.example.HoW_Memento;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.*;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

/**
 * Created with IntelliJ IDEA.
 * User: jm_win7
 * Date: 07/10/13
 * Time: 18:41
 * To change this template use File | Settings | File Templates.
 */

public class CardsListViewActivity extends SherlockActivity {

    ListView list;
    ListCardAdapter adapter;
    ArrayList<CardEntry> cards = null;
    // nom des tags XML
    private final String CARD = "Card";
    private final String NAME = "Name";
    private final String CLASS = "Class";
    private final String COST = "Cost";
    private final String ATTACK = "Attack";
    private final String HEALTH = "Health";
    private final String URL = "ImageURL";

    private SlidingMenu slidingMenu;

        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_cardslistview);


            ActionBar bar = getSupportActionBar();
            bar.setDisplayHomeAsUpEnabled(true);
            bar.setHomeButtonEnabled(true);
            bar.setDisplayShowTitleEnabled(true);
            bar.setTitle("Cards List");

            initImageLoader(getApplicationContext());

            slidingMenu = new SlidingMenu(this);
            slidingMenu.setMode(SlidingMenu.LEFT);
            slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
            slidingMenu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
            slidingMenu.setFadeDegree(0.85f);
            slidingMenu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
            slidingMenu.setMenu(R.layout.sliding_crit_menu);


            XmlPullParserFactory pullParserFactory;
            try {
                pullParserFactory = XmlPullParserFactory.newInstance();
                XmlPullParser parser = pullParserFactory.newPullParser();

                InputStream in_s = getApplicationContext().getAssets().open("HoWDB191013.xml");
                parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
                parser.setInput(in_s, null);

                parseXML(parser);

                final ListView listview = (ListView) findViewById(R.id.listview);

                updateListCardShowed(listview,cards) ;

                listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> parent, final View view,
                                            int position, long id) {
                        Toast.makeText(getApplicationContext(),"You selected : " + position,Toast.LENGTH_SHORT).show();
                    }

                });
                final Button startSearchButton = (Button)findViewById(R.id.search_button);

                startSearchButton.setOnClickListener(
                        new View.OnClickListener()
                        {
                            public void onClick(View aView)
                            {

                                 CardFilterCriterias crittest = GetCriteria();
                                 ArrayList<CardEntry> cardstest = CardXMLTools.filterByCriteria(cards,crittest);
                                 slidingMenu.toggle();
                                updateListCardShowed(listview,cardstest) ;
                            }
                        }
                );
            } catch (XmlPullParserException e) {

                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
        }
        }

    private CardFilterCriterias GetCriteria() {
        CardFilterCriterias criterias = new CardFilterCriterias();

        EditText edittext = (EditText) findViewById(R.id.cardname_filteredittext);
        criterias.setCritName(edittext.getText().toString());
        Spinner spinnerBuff = (Spinner) findViewById(R.id.cardclass_spinner);
        criterias.setCritClass(spinnerBuff.getSelectedItem().toString());
        spinnerBuff = (Spinner) findViewById(R.id.cardcost_spinner);
        criterias.setCritCost(spinnerBuff.getSelectedItem().toString());
        spinnerBuff = (Spinner) findViewById(R.id.cardattack_spinner);
        criterias.setCritAttack(spinnerBuff.getSelectedItem().toString());
        spinnerBuff = (Spinner) findViewById(R.id.cardhealth_spinner);
        criterias.setCritHealth(spinnerBuff.getSelectedItem().toString());

        return criterias;


    }

    private void updateListCardShowed(ListView lv,ArrayList<CardEntry> cardsToShow) {
        final ListCardAdapter adapter = new ListCardAdapter(this,cardsToShow);
        lv.setAdapter(adapter);
    }

    private void parseXML(XmlPullParser parser) throws XmlPullParserException,IOException
    {

        int eventType = parser.getEventType();
        CardEntry currentCard = null;

        while (eventType != XmlPullParser.END_DOCUMENT){
            String name = null;
            switch (eventType){
                case XmlPullParser.START_DOCUMENT:
                    cards = new ArrayList();
                    break;
                case XmlPullParser.START_TAG:
                    name = parser.getName();
                    if (name.equals(CARD)){
                        currentCard = new CardEntry();
                    }
                    if (name.equals(NAME)){
                        currentCard.setCardName(parser.nextText());
                    }
                    if (name.equals(CLASS)){
                        currentCard.setCardClass(parser.nextText());
                    }

                    if (name.equals(COST)){
                        currentCard.setCardCost(parser.nextText());
                    }

                    if (name.equals(ATTACK)){
                        currentCard.setCardAttack(parser.nextText());
                    }

                    if (name.equals(HEALTH)){
                        currentCard.setCardHealth(parser.nextText());
                    }

                    if (name.equals(URL)){
                        currentCard.setCardImageurl(parser.nextText());
                    }

                    break;
                case XmlPullParser.END_TAG:
                    name = parser.getName();
                    if (name.equalsIgnoreCase("card") && currentCard != null){
                        cards.add(currentCard);
                    }
            }
            eventType = parser.next();
        }
    }
    public static void initImageLoader(Context context) {

        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
                .threadPriority(Thread.NORM_PRIORITY - 2)
                .denyCacheImageMultipleSizesInMemory()
                .discCacheFileNameGenerator(new Md5FileNameGenerator())
                .tasksProcessingOrder(QueueProcessingType.LIFO)
                .build();

        ImageLoader.getInstance().init(config);
    }


 //region Méthode pour Sliding Menu

    @Override
    public void onBackPressed() {
        if ( slidingMenu.isMenuShowing()) {
            slidingMenu.toggle();
        }
        else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ( keyCode == KeyEvent.KEYCODE_MENU ) {
            this.slidingMenu.toggle();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    //endregion

}